#include "cpool.h"

void cpool_init()
{  
	cpool.found=false;
	if((cpool.sockfd =socket(AF_INET,SOCK_STREAM,0))< 0) lprintf(log, FATAL," cpool init socket fatal!!\n");
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr =inet_addr(SERVER_IP);
	serv_addr.sin_port = htons(TIME_PORT);  
	if (connect(cpool.sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)	
		lprintf(log, FATAL,"cpool init connect fatal!!\n");
	else	cpool.found=true;
	//if(! cpool.found) return cpool_init();
}

/* query mysql pool */
void cpool_query(char *sql)
{
	int	len;
	char	buf[SIZE]={0};  
	//printf("%s\n",sql);
	sprintf(buf,"%s;\r\n",sql);
	len=send(cpool.sockfd, buf,sizeof(buf), 0);
	if (len < 0) perror("sendto"),exit(1);
	while(1)
	{
		bzero(cpool.buffer,sizeof(cpool.buffer));
		len=recv(cpool.sockfd,cpool.buffer,sizeof(cpool.buffer),0);
		//if (len <= 0) perror("recv"),exit(1);
		//printf("%s\n",cpool.buffer);
		if( strstr(cpool.buffer, "OK" )) break; 
		else 
		{
			lprintf(flog, FATAL,"%s;\n",sql);
			break;
		}
	}
}

void mysql_Connect( char *fmt,...)
{
	va_list ap;
	static char line[ SIZE ]={0};
	
	va_start(ap, fmt);
  	vsnprintf(line ,sizeof( line ), fmt, ap);
  	va_end(ap);
  	
  	line[ sizeof(line)-1 ] = '\0';
	if(! cpool.found ) lprintf(flog, FATAL,"%s\n", line);
	else cpool_query( line ); 
	
}
